﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using EPiServer.DataAbstraction;
using EPiSugar.EntityAdapter.PropertyBinders;

namespace EPiSugar.EntityAdapter
{
    public class BindToReferenceAttribute : Attribute, IBinderFactory
    {
        private readonly string propertyName;

        public BindToReferenceAttribute()
        {
        }
        public BindToReferenceAttribute(string propertyName)
        {
            this.propertyName = propertyName;
        }

        public IPropertyBinder CreateBinder(PageDefinitionCollection propertyDefinitions, PropertyInfo destinationProperty)
        {
            string sourceProperty = propertyName;
            if(sourceProperty == null)
                sourceProperty = (from p in propertyDefinitions where p.Name == destinationProperty.Name select p.Name).FirstOrDefault();
            if(sourceProperty == null)
                throw new ApplicationException("Found no property definition on the page type with the name " + destinationProperty.Name);

            return new ReferenceBinder(sourceProperty, destinationProperty);
        }
    }
}
